<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
            <el-form-item label="乡村名" prop="villageName">
                <el-input v-model="queryParams.villageName" placeholder="请输入乡村名" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="乡村地址" prop="villageAddress">
                <el-input v-model="queryParams.villageAddress" placeholder="请输入乡村地址" clearable size="small"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="乡村标签" prop="villageLabel">
                <el-select v-model="queryParams.villageLabel" placeholder="请选择乡村标签" clearable size="small">
                    <el-option v-for="dict in villageLabelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="乡村等级" prop="villageGrade">
                <el-select v-model="queryParams.villageGrade" placeholder="请选择乡村等级" clearable size="small">
                    <el-option v-for="dict in villageGradeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="权重" prop="weight">
                <el-select v-model="queryParams.weight" placeholder="请选择权重" clearable size="small">
                    <el-option v-for="dict in weightOptions" :key="dict.dictValue" :label="dict.dictLabel"
                        :value="dict.dictValue" />
                </el-select>
            </el-form-item>
            <el-form-item label="数据年份" prop="year">
                <el-date-picker type="year" align="right" v-model="queryParams.year" format="yyyy" value-format="yyyy"
                    placeholder="请选择数据年份" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['route:village:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['route:village:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['route:village:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['route:village:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-top" size="mini" @click="handleImport"
                    v-hasPermi="['route:village:import']">导入</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <!-- 导入文件组件 -->
        <FileImport ref="importDataDialog" :title="'导入文件'" :action="baseUrl + '/route/village/import'"
            :accept="'.xls,.xlsx'" @uploadSuccess="importDataSuccess" />

        <el-table v-loading="loading" :data="villageList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="乡村主键id" align="center" v-if="false" prop="id" />
            <el-table-column label="介绍" prop="villageIntroduce" type="expand">
                <template slot-scope="scope">
                    <el-form label-position="left" inline class="demo-table-expand">
                        <el-form-item label="乡村介绍">
                            <div v-html="scope.row.villageIntroduce"></div>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="名称" align="center" prop="villageName" />
            <el-table-column label="地址" align="center" prop="villageAddress" />
            <el-table-column label="标签" align="center" prop="villageLabel">
                <template slot-scope="scope">
                    <el-tag type="success" v-for="item in dictEcho(scope.row.villageLabel, villageLabelOptions)"
                        :key="item.dictValue">{{ item.dictLabel }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="经度" align="center" prop="longitude" />
            <el-table-column label="纬度" align="center" prop="latitude" />
            <el-table-column label="图片" align="center" prop="villageImage">
                <template slot-scope="scope">
                    <span v-for="(item, index) in scope.row.villageImage" :key="index">
                        <el-image fit="fit" :src="baseUrl + item" :preview-src-list="[baseUrl + item]"
                            style="width:50px;height:50px;" />
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="等级" align="center" prop="villageGrade">
                <template slot-scope="scope">
                    <el-tag
                        :type="scope.row.villageGrade === '0' ? 'danger' : scope.row.villageGrade === '1' ? 'success' : 'warning'"
                        v-for="item in dictEcho(scope.row.villageGrade, villageGradeOptions)" :key="item.dictValue">{{
                            item.dictLabel
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="权重" align="center" prop="weight">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.weight === '0' ? 'danger' : scope.row.weight === '1' ? 'success' : 'info'"
                        v-for="item in dictEcho(scope.row.weight, weightOptions)" :key="item.dictValue">{{ item.dictLabel
                        }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="行政区划" align="center" prop="mgyArea" />
            <el-table-column label="数据年份" align="center" prop="year" />
            <el-table-column label="创建时间" align="center" prop="createTime" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['route:village:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['route:village:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改乡村数据对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="名称" prop="villageName">
                    <el-input v-model="form.villageName" placeholder="请输入乡村名称" />
                </el-form-item>
                <el-form-item label="标签" prop="villageLabel">
                    <el-select v-model="form.villageLabel" clearable multiple placeholder="请选择乡村标签" style="width:100%;">
                        <el-option v-for="dict in villageLabelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="地址" prop="villageAddress">
                    <MAP :value="form.lngLat" :address="form.villageAddress" @input="mapClick"></MAP>
                </el-form-item>
                <el-form-item label="图片" prop="villageImage">
                    <ImageUpload v-model="form.villageImage" @uploadImage="uploadImg" @remove="uploadImg" :limit="9" />
                </el-form-item>
                <el-form-item label="等级" prop="villageGrade">
                    <el-select v-model="form.villageGrade" placeholder="请选择乡村等级">
                        <el-option v-for="dict in villageGradeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="介绍" prop="villageIntroduce">
                    <el-input type="textarea" :rows="5" v-model="form.villageIntroduce" placeholder="请输入内容" />
                </el-form-item>
                <!-- prop="weight" -->
                <el-form-item label="权重">
                    <el-select v-model="form.weight" placeholder="请选择权重">
                        <el-option v-for="dict in weightOptions" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据年份" prop="year">
                    <el-date-picker type="year" align="right" v-model="form.year" format="yyyy" value-format="yyyy"
                        placeholder="请选择数据年份" :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
  
<script>
import { listVillage, getVillage, delVillage, addVillage, updateVillage, exportVillage } from "@/api/route/village";
import ImageUpload from "@/components/UploadImage/index.vue";
import FileImport from "@/components/FileImport/index.vue"
import MAP from "@/components/map/index";

export default {
    name: "Village",
    dicts: ["village_grade"],
    components: {
        ImageUpload,
        MAP,
        FileImport,
    },
    data() {
        return {
            //图片地址
            baseUrl: process.env.VUE_APP_BASE_API,
            //时间选择器快捷选择数据
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 乡村数据表格数据
            villageList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 乡村等级字典
            villageGradeOptions: [],
            // 权重字典
            weightOptions: [],
            // 乡村标签字典
            villageLabelOptions: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                villageName: null,
                villageAddress: null,
                longitude: null,
                latitude: null,
                villageImage: null,
                villageGrade: null,
                villageIntroduce: null,
                weight: null,
                villageLabel: null,
                province: null,
                city: null,
                county: null,
                year: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                villageName: [{ required: true, message: '请输入乡村名', trigger: 'blur' }],
                lnglat: [{ required: true, message: '请选择乡村地址', trigger: 'blur' }],
                villageImage: [{ required: true, message: '请上传乡村图片', trigger: 'blur' }],
                villageGrade: [{ required: true, message: '请选择乡村等级', trigger: 'blur' }],
                villageIntroduce: [{ required: true, message: '请输入乡村介绍', trigger: 'blur' }],
                weight: [{ required: true, message: '请选择权重', trigger: 'blur' }],
                villageLabel: [{ required: true, message: '请选择乡村标签', trigger: 'blur' }],
                year: [{ required: true, message: '请选择年份', trigger: 'change' }],
            }
        };
    },
    created() {
        this.getList();
        this.getDicts("village_grade").then(response => {
            this.villageGradeOptions = response.data;
        });
        this.getDicts("weight").then(response => {
            this.weightOptions = response.data;
        });
        this.getDicts("village_label").then(response => {
            this.villageLabelOptions = response.data;
        });
    },
    methods: {
        /** 查询乡村数据列表 */
        getList() {
            this.loading = true;
            listVillage(this.queryParams).then(response => {
                this.villageList = response.rows.map(item => ({
                    ...item,
                    villageImage: item.villageImage ? item.villageImage.split(",") : [],
                }));
                this.total = response.total;
                this.loading = false;
            });
        },
        // 乡村等级字典翻译
        villageGradeFormat(row, column) {
            return this.selectDictLabel(this.villageGradeOptions, row.villageGrade);
        },
        // 权重字典翻译
        weightFormat(row, column) {
            return this.selectDictLabel(this.weightOptions, row.weight);
        },
        // 乡村标签字典翻译
        villageLabelFormat(row, column) {
            return this.selectDictLabel(this.villageLabelOptions, row.villageLabel);
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                villageName: undefined,
                villageAddress: undefined,
                longitude: undefined,
                latitude: undefined,
                villageImage: undefined,
                villageGrade: undefined,
                villageIntroduce: undefined,
                weight: undefined,
                villageLabel: undefined,
                province: undefined,
                city: undefined,
                county: undefined,
                createTime: undefined,
                tenantId: undefined,
                lngLat: undefined,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加乡村数据";
        },
        //乡村图片上传图片组件成功回调函数
        uploadImg(e) {
            this.form.villageImage = e;
        },
        /* 乡村地址地图选点组件成功回调函数 */
        mapClick(e) {
            console.log(e, 'eeee');
            this.form.villageAddress = e.formattedAddress;
            this.form.lngLat = e.lnglat;
            this.form.longitude = e.lnglat.slice(0, e.lnglat.indexOf(","));
            this.form.latitude = e.lnglat.slice(e.lnglat.indexOf(",") + 1, e.lnglat.length);
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getVillage(id).then(response => {
                response.data.villageLabel = response.data.villageLabel ? response.data.villageLabel.split(",") : [];
                response.data.lngLat = response.data.longitude + "," + response.data.latitude;
                this.form = response.data;
                this.open = true;
                this.title = "修改乡村数据";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let data = { ...this.form };
                    data.villageLabel = data.villageLabel.toString();
                    if (this.form.id != null) {
                        updateVillage(data).then(response => {
                            this.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addVillage(data).then(response => {
                            this.msgSuccess(response.msg);
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除乡村名称为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delVillage(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有乡村数据数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportVillage(queryParams);
            }).then(response => {
                this.download(response.msg);
            })
        },
        /** 导入按钮操作 */
        handleImport() {
            this.$refs.importDataDialog.openDialog();
        },
        /** 导入文件组件成功回调函数 */
        importDataSuccess(e) {
            this.getList();
        },
    }
};
</script>